<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request"

const router = useRouter()
const formRef = ref()

// 本地存储键名
const STORAGE_KEY = 'plans-data'

// 计划数据
const plans = ref([])
const loading = ref(false)

// 测试数据 - 当API调用失败时使用
const testPlans = [
  {
    id: 1,
    name: "数据结构复习",
    date: "2023-05-20",
    startTime: "09:00",
    endTime: "11:30",
    type: "single",
    content: "复习二叉树、图论和排序算法",
    cycle: null,
    cycleNumber: null,
    cycleUnit: null,
    startDate: null,
    endDate: null
  },
  {
    id: 2,
    name: "算法练习",
    date: "2023-05-20",
    startTime: "14:00",
    endTime: "16:30",
    type: "single",
    content: "完成LeetCode中5道中等难度算法题",
    cycle: null,
    cycleNumber: null,
    cycleUnit: null,
    startDate: null,
    endDate: null
  },
  {
    id: 3,
    name: "每日英语学习",
    date: "2023-05-21",
    startTime: "08:00",
    endTime: "09:00",
    type: "periodic",
    content: "学习20个新单词，阅读一篇英语文章",
    cycle: "1 days",
    cycleNumber: 1,
    cycleUnit: "days",
    startDate: "2023-05-01",
    endDate: "2023-06-30"
  },
  {
    id: 4,
    name: "操作系统实验",
    date: "2023-05-22",
    startTime: "19:00",
    endTime: "21:00",
    type: "single",
    content: "完成进程调度算法模拟实验",
    cycle: null,
    cycleNumber: null,
    cycleUnit: null,
    startDate: null,
    endDate: null
  },
  {
    id: 5,
    name: "周末复习计划",
    date: "2023-05-27",
    startTime: "09:30",
    endTime: "11:30",
    type: "periodic",
    content: "复习本周所学内容，整理笔记",
    cycle: "7 days",
    cycleNumber: 7,
    cycleUnit: "days",
    startDate: "2023-05-01",
    endDate: "2023-07-31"
  }
]

// 获取学生ID
const getStuId = () => {
    try {
        const rawInfo = localStorage.getItem('studentUserInfo')
        if (!rawInfo) {
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return null
        }

        const userInfo = JSON.parse(rawInfo)
        if (!userInfo?.stu_id) {
            localStorage.removeItem('studentUserInfo')
            ElMessage.warning('登录信息无效，请重新登录')
            router.push('/student/login')
            return null
        }
        return userInfo.stu_id
    } catch (e) {
        console.error('学生ID获取失败:', e)
        ElMessage.error('登录信息解析失败')
        router.push('/student/login')
        return null
    }
}

// 获取用户名
const getUsername = () => {
    try {
        const rawInfo = localStorage.getItem('studentUserInfo')
        if (!rawInfo) return null

        const userInfo = JSON.parse(rawInfo)
        return userInfo?.username || null
    } catch (e) {
        return null
    }
}

// 从API加载计划数据
const loadPlans = async () => {
    try {
        loading.value = true
        console.log('开始加载计划数据...')

        const userId = getStuId()
        const username = getUsername()

        if (!userId && !username) {
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return
        }

        const params = {}

        // 优先使用用户名，其次使用学生ID
        if (username) {
            params.username = username
        } else if (userId) {
            params.stu_id = userId
        }

        console.log('请求参数:', params)

        try {
            const response = await request.get('/api/student/study-plan/all/', {
                params,
                timeout: 8000
            })

            console.log('计划数据响应:', response)

            if (response.data && Array.isArray(response.data)) {
                plans.value = response.data.map(plan => ({
                    id: plan.plan_id,
                    name: plan.plan_name,
                    date: plan.plan_date,
                    startTime: plan.start_time,
                    endTime: plan.end_time,
                    type: plan.plan_type || 'single',
                    content: plan.plan_content,
                    cycle: plan.plan_type === 'periodic' ? `${plan.cycle_value} ${plan.cycle_unit}` : null,
                    cycleNumber: plan.cycle_value,
                    cycleUnit: plan.cycle_unit,
                    startDate: plan.start_date,
                    endDate: plan.end_date
                }))
                console.log('成功加载计划数据，条数:', plans.value.length)
            } else {
                console.warn('返回的计划数据格式不正确:', response.data)
                ElMessage.warning('加载计划数据格式不正确，使用测试数据')
                plans.value = testPlans
            }
        } catch (apiError) {
            console.error('API请求失败:', apiError)
            ElMessage.warning('加载计划数据失败，使用测试数据')
            plans.value = testPlans
        }
    } catch (error) {
        console.error('获取计划数据失败:', error)
        ElMessage.warning('加载计划数据失败，使用测试数据')
        plans.value = testPlans
    } finally {
        loading.value = false
    }
}

// 抽屉相关状态
const drawerVisible = ref(false)
const currentPlan = reactive({
    id: null,
    name: '',
    date: '',
    startTime: '',
    endTime: '',
    type: 'single',
    content: '',
    cycle: null,
    cycleNumber: 1,
    cycleUnit: 'days',
    startDate: null,
    endDate: null
})

// 计算唯一日期
const uniqueDates = computed(() => {
    return [...new Set(plans.value.map(plan => plan.date))].sort()
})

// 方法
const Back = () => router.go(-1)
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

const getPlansByDate = (date) => {
    return plans.value
        .filter(plan => plan.date === date)
        .sort((a, b) => a.startTime.localeCompare(b.startTime))
}

const openDrawer = (plan) => {
    if (plan.cycle) {
        const [number, unit] = plan.cycle.split(' ')
        currentPlan.cycleNumber = parseInt(number)
        currentPlan.cycleUnit = unit
    }

    Object.assign(currentPlan, {
        ...plan,
        startDate: plan.startDate || null,
        endDate: plan.endDate || null,
        cycle: plan.cycle || null
    })
    drawerVisible.value = true
}

const formatTime = (time) => {
    if (!time) return ''
    const [hours, minutes] = time.split(':')
    const date = new Date()
    date.setHours(hours)
    date.setMinutes(minutes)
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    })
}
// 表单验证规则
const rules = {
    name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    date: [{ required: true, message: '请选择日期', trigger: 'change' }],
    type: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
    content: [{ required: true, message: '请输入计划内容', trigger: 'blur' }]
}

const timeRules = {
    startTime: [
        {
            validator: (rule, value, callback) => {
                if (!value) return callback(new Error('请选择开始时间'))
                if (currentPlan.endTime && value > currentPlan.endTime) {
                    return callback(new Error('开始时间不能晚于结束时间'))
                }
                callback()
            },
            trigger: 'change'
        }
    ],
    endTime: [
        {
            validator: (rule, value, callback) => {
                if (!value) return callback(new Error('请选择结束时间'))
                if (currentPlan.startTime && value < currentPlan.startTime) {
                    return callback(new Error('结束时间不能早于开始时间'))
                }
                callback()
            },
            trigger: 'change'
        }
    ],
    cycleNumber: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (currentPlan.type === 'periodic' && (!value || value < 1)) {
                    callback(new Error('请输入有效的周期数值'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    cycleUnit: [
        {
            required: true,
            message: '请选择周期单位',
            trigger: 'change',
            validator: (rule, value, callback) => {
                if (currentPlan.type === 'periodic' && !value) {
                    callback(new Error('请选择周期单位'))
                } else {
                    callback()
                }
            }
        }
    ],
    startDate: [
        {
            required: true,
            message: '请选择开始日期',
            trigger: 'change',
            validator: (rule, value, callback) => {
                if (currentPlan.type === 'periodic' && !value) {
                    callback(new Error('请选择开始日期'))
                } else {
                    callback()
                }
            }
        }
    ],
    endDate: [
        {
            required: true,
            message: '请选择结束日期',
            trigger: 'change',
            validator: (rule, value, callback) => {
                if (currentPlan.type === 'periodic') {
                    if (!value) {
                        return callback(new Error('请选择结束日期'))
                    }
                    if (new Date(value) < new Date(currentPlan.startDate)) {
                        return callback(new Error('结束日期不能早于开始日期'))
                    }
                }
                callback()
            }
        }
    ]
}

// 删除计划
const deletePlan = () => {
    ElMessageBox.confirm('确定要删除这个计划吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            if (currentPlan.id) {
                try {
                    await request.delete(`/api/student/study-plan/${currentPlan.id}/`)
                    ElMessage.success('删除成功')
                    // 重新加载数据
                    await loadPlans()
                } catch (apiError) {
                    console.error('API删除请求失败，使用本地测试数据处理:', apiError)

                    // 模拟删除操作
                    plans.value = plans.value.filter(p => p.id !== currentPlan.id)
                    ElMessage.success('模拟删除成功')
                }
            } else {
                ElMessage.error('删除失败：计划ID无效')
            }
            drawerVisible.value = false
        } catch (error) {
            console.error('删除计划失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }).catch(() => {})
}

// 修改后的保存方法
const savePlan = async () => {
    try {
        await formRef.value.validate()

        const userId = getStuId()
        const username = getUsername()

        if (!userId && !username) {
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return
        }

        // 准备提交的计划数据
        const planData = {
            plan_name: currentPlan.name,
            plan_date: currentPlan.date,
            plan_type: currentPlan.type,
            start_time: currentPlan.startTime,
            end_time: currentPlan.endTime,
            plan_content: currentPlan.content
        }

        // 添加周期相关数据
        if (currentPlan.type === 'periodic') {
            planData.cycle_value = currentPlan.cycleNumber
            planData.cycle_unit = currentPlan.cycleUnit
            planData.start_date = currentPlan.startDate
            planData.end_date = currentPlan.endDate
        }

        // 添加用户标识
        if (username) {
            planData.username = username
        }
        if (userId) {
            planData.stu_id = userId
        }

        console.log('保存计划数据:', planData)

        try {
            let response
            if (currentPlan.id) {
                // 更新现有计划
                response = await request.put(`/api/student/study-plan/${currentPlan.id}/`, planData)
            } else {
                // 创建新计划
                response = await request.post('/api/student/study-plan/', planData)
            }

            console.log('保存计划响应:', response)

            if (response.status === 200 || response.status === 201) {
                ElMessage.success(currentPlan.id ? '更新成功' : '添加成功')
                drawerVisible.value = false
                // 重新加载数据
                await loadPlans()
            } else {
                ElMessage.error(response.data?.error || '保存失败')
            }
        } catch (apiError) {
            console.error('API请求失败，使用本地测试数据处理:', apiError)

            // 使用测试数据模拟保存操作
            if (currentPlan.id) {
                // 模拟更新现有计划
                const index = plans.value.findIndex(p => p.id === currentPlan.id)
                if (index !== -1) {
                    plans.value[index] = { ...currentPlan }
                }
            } else {
                // 模拟创建新计划
                const newId = Math.max(...plans.value.map(p => p.id), 0) + 1
                plans.value.push({
                    id: newId,
                    name: currentPlan.name,
                    date: currentPlan.date,
                    startTime: currentPlan.startTime,
                    endTime: currentPlan.endTime,
                    type: currentPlan.type,
                    content: currentPlan.content,
                    cycle: currentPlan.type === 'periodic' ? `${currentPlan.cycleNumber} ${currentPlan.cycleUnit}` : null,
                    cycleNumber: currentPlan.cycleNumber,
                    cycleUnit: currentPlan.cycleUnit,
                    startDate: currentPlan.startDate,
                    endDate: currentPlan.endDate
                })
            }

            ElMessage.success(currentPlan.id ? '模拟更新成功' : '模拟添加成功')
            drawerVisible.value = false
        }
    } catch (error) {
        console.error('保存计划失败:', error)
        ElMessage.error('保存失败，请检查输入')
    }
}

// 添加新计划
const addNewPlan = () => {
    // 重置当前计划数据
    Object.assign(currentPlan, {
        id: null,
        name: '',
        date: new Date().toISOString().split('T')[0], // 默认为今天
        startTime: '',
        endTime: '',
        type: 'single',
        content: '',
        cycle: null,
        cycleNumber: 1,
        cycleUnit: 'days',
        startDate: null,
        endDate: null
    })

    // 显示抽屉
    drawerVisible.value = true
}

// 初始化：加载数据
onMounted(() => {
    loadPlans()
})

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <div class="plan-container">
        <div class="header">
            <div class="nav-buttons">
                <el-button type="primary" link @click="Back">返回上一页</el-button>
                <el-button type="primary" link @click="backToHome">返回主页</el-button>
            </div>
            <h2 class="page-title">个人学习计划</h2>
            <el-button type="primary" @click="addNewPlan">创建新计划</el-button>
        </div>

        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="plans.length === 0" class="empty-container">
            <el-empty description="暂无计划数据" />
        </div>
        <div v-else class="timeline-table">
            <div class="table-header">
                <div v-for="date in uniqueDates" :key="date" class="date-column">
                    {{ date }}
                </div>
            </div>

            <div class="table-body">
                <div v-for="date in uniqueDates" :key="date" class="date-column">
                    <el-card
                        v-for="plan in getPlansByDate(date)"
                        :key="plan.id"
                        class="plan-card"
                        @click="openDrawer(plan)"
                    >
                        <h4>{{ plan.name }}</h4>
                        <p>{{ formatTime(plan.startTime) }} - {{ formatTime(plan.endTime) }}</p>
                        <el-tag v-if="plan.type === 'periodic'" size="small" type="warning">周期计划</el-tag>
                        <p class="plan-content">{{ plan.content }}</p>
                    </el-card>
                </div>
            </div>
        </div>

        <el-drawer v-model="drawerVisible" title="计划详情" direction="rtl" size="40%">
            <el-form
                :model="currentPlan"
                label-width="100px"
                :rules="rules"
                ref="formRef"
            >
                <el-form-item label="计划名称" prop="name">
                    <el-input v-model="currentPlan.name" />
                </el-form-item>

                <el-form-item label="计划日期" prop="date">
                    <el-date-picker
                        v-model="currentPlan.date"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>

                <el-form-item label="计划类型" prop="type">
                    <el-select v-model="currentPlan.type">
                        <el-option label="单次计划" value="single" />
                        <el-option label="周期计划" value="periodic" />
                    </el-select>
                </el-form-item>

                <template v-if="currentPlan.type === 'periodic'">
                    <el-form-item label="周期数值" prop="cycleNumber">
                        <el-input-number
                            v-model="currentPlan.cycleNumber"
                            :min="1"
                            :max="100"
                            controls-position="right"
                        />
                    </el-form-item>

                    <el-form-item label="周期单位" prop="cycleUnit">
                        <el-select v-model="currentPlan.cycleUnit">
                            <el-option label="小时" value="hours" />
                            <el-option label="天" value="days" />
                            <el-option label="周" value="weeks" />
                            <el-option label="月" value="months" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="开始日期" prop="startDate">
                        <el-date-picker
                            v-model="currentPlan.startDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>

                    <el-form-item label="结束日期" prop="endDate">
                        <el-date-picker
                            v-model="currentPlan.endDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </template>

                <el-form-item
                    label="开始时间"
                    prop="startTime"
                    :rules="timeRules.startTime"
                >
                    <el-time-picker
                        v-model="currentPlan.startTime"
                        format="HH:mm"
                        value-format="HH:mm"
                        :disabled="!currentPlan.date"
                    />
                </el-form-item>

                <el-form-item
                    label="结束时间"
                    prop="endTime"
                    :rules="timeRules.endTime"
                >
                    <el-time-picker
                        v-model="currentPlan.endTime"
                        format="HH:mm"
                        value-format="HH:mm"
                        :disabled="!currentPlan.date"
                    />
                </el-form-item>
                <el-form-item label="计划内容" prop="content">
                    <el-input v-model="currentPlan.content" type="textarea" rows="4" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="savePlan">保存</el-button>
                    <el-button v-if="currentPlan.id" type="danger" @click="deletePlan">
                        删除
                    </el-button>
                    <el-button @click="drawerVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
    <div class="chat-bubble" @click="toggleChat">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">
    </div>

    <div class="chat-container" id="chatContainer">
        <iframe src="http://121.40.242.43/chatbot/Ql1E9ZJwmiDKRNTM" class="chat-iframe"></iframe>
    </div>
</template>

<style scoped>
.plan-container {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.nav-buttons {
    display: flex;
    align-items: center;
}

.page-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    margin: 0;
    font-size: 1.5rem;
}

.loading-container,
.empty-container {
    padding: 40px 20px;
    text-align: center;
}

.timeline-table {
    display: grid;
    overflow-x: auto;
}

.table-header {
    display: flex;
    background: #f5f7fa;
}

.date-column {
    min-width: 250px;
    padding: 10px;
    border-right: 1px solid #ebeef5;
}

.table-body {
    display: flex;
    min-height: 500px;
}

.plan-card {
    margin-bottom: 10px;
    padding: 8px;
    transition: all 0.3s;
    cursor: pointer;
}

.plan-card h4 {
    margin: 0 0 8px 0;
    font-size: 14px;
}

.plan-card p {
    margin: 0;
    font-size: 12px;
    color: #666;
}

.plan-content {
    margin-top: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.plan-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-time-picker {
    width: 100%;
}

.el-form-item {
    margin-bottom: 18px;
}

.el-input-number {
    width: 150px;
}
#dify-chatbot-bubble-button {
    background-color: #1C64F2 !important;
  }
#dify-chatbot-bubble-window {
    width: 24rem !important;
    height: 40rem !important;
  }
  .chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
